package graphics;

import java.awt.Point;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

import logger.Logger;
import util.DrawSet;

public class Graphics2D {
	
	public static final Set<Point>	getTriangleFill(Point P1, Point P2, Point P3) {
		Set<Point>	visited = new HashSet<Point>();
		
		Point 			start	= new Point((P1.x + P2.x + P3.x)/3, (P1.y + P2.y + P3.y)/3);
		Stack<Point>	fringe	= new Stack<Point>();
		fringe.add(start);
		
		while(!fringe.isEmpty()) {
			Point P = fringe.pop();
			if (contains(P1, P2, P3, P) && !visited.contains(P)) {
				visited.add(P);
				fringe.addAll(DrawSet.getAdjacent(P));
			}
		}
		return visited;
	}
	
	public static float	ccwFloat(Point A, Point B, Point C) {
		float	d1[] = new float[] {
			(float) (C.getX() - A.getX()),
			(float) (C.getY() - A.getY())
		};
		float	d2[] = new float[] {
			(float) (C.getX() - B.getX()),
			(float) (C.getY() - B.getY())
		};
		float	z = (d1[0]*d2[1]) - (d1[1]*d2[0]);
		return z;
	}
	
	public static int ccw(Point a, Point b, Point c) {
		float	ccwF = ccwFloat(a,b,c);
		if (ccwF<0)	return -1;
		if (ccwF>0) return 1;
		return 0;
	}
	
	public static float	distance(Point A, Point B) {
		return (float) Math.sqrt(
			(B.getX()-A.getX())*(B.getX()-A.getX())
		+	(B.getY()-A.getY())*(B.getY()-A.getY())
		);
	}
	public static boolean colinear(Point A, Point B, Point C) throws Exception {
		return (ccw(A,B,C)==0f);
	}
	public static boolean intersect(Point lineAstart, Point lineAend, Point lineBstart, Point lineBend) throws Exception {
		float	test1, test2;
		test1 = ccw(lineAstart, lineAend, lineBstart) * ccw(lineAstart, lineAend, lineBend);
		test2 = ccw(lineBstart, lineBend, lineAstart) * ccw(lineBstart, lineBend, lineAend);
		return (test1 <= 0f) && (test2 <= 0f);
	}
	public static boolean contains(Point A, Point B, Point C, Point T) {
		try {
			if (ccw(A,B,C) < 0) {
				return contains(C,B,A,T);
			} else {
				float test1 = ccw(A,B,T);
				float test2 = ccw(B,C,T);
				float test3 = ccw(C,A,T);
				return ((test1 >= 0f) && (test2 >= 0f) && (test3 >= 0f));
			}
		} catch (Exception e) {
			Logger.println("I dont know what happened, but its safe to assume its not in the triangle");
			return false;
		}
	}
}
